<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="机器码" prop="phoneSn">
        <el-input
          v-model="queryParams.phoneSn"
          placeholder="请输入机器码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="dateRange"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right">
        </el-date-picker>
      </el-form-item>



      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClean"
          v-hasPermi="['api:location:remove']"
        >清空数据</el-button>
      </el-form-item>
    </el-form>

    <div style="width: 100%;height: 700px;">
      <el-amap vid="amap" :plugin="plugin"  :center="center" :zoom="zoom">
        <el-amap-marker style="width: 10px;height: 10px" v-for="(marker, index) in locationList"
                        :position="marker.position" :key="index" :title="marker.createTime">
        </el-amap-marker>

        <el-amap-polyline v-for="prod in polylineList"
                          :key="prod.id"
                          :path="prod.path"
                          outlineColor='#fff000'
                          strokeWeight='2'>
        </el-amap-polyline>
      </el-amap>
    </div>
    <div class="center-in-center div1">
      <div v-if="lastMarkerOption !=null">
        <p>机器码：{{lastMarkerOption.phoneSn}}</p>
        <p>最后一次记录时间：{{lastMarkerOption.createTime}}</p>
      </div>
      <div v-else>
        <p>机器码：没有记录的机器码</p>
        <p>最后一次记录时间：无</p>
      </div>
    </div>
  </div>
</template>

<script>
  import { listLocation, getLocation, delLocation, addLocation, updateLocation,cleanOperLocation } from "@/api/api/location";
  import AMap from 'vue-amap';

  export default {
    name: "Location",
    data() {
      const self = this
      return {
        lastMarkerOption: undefined,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 电话位置表格数据
        locationList: [],
        // 折线列表数据
        polylineList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: null,
          longitude: null,
          latitude: null,
          recordTime: null,
          phoneSn: null,
          startTime: null,
          endTime: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
        },
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        // 日期范围
        dateRange: "",
        gd_instance: {},
        center: [125.338633, 43.861247],
        lng: 0,
        lat: 0,
        loaded: false,
        zoom: 11,
        markers: [],
        plugin: [
          {
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 0,          //超过10秒后停止定位，默认：无穷大
            maximumAge: 0,           //定位结果缓存0毫秒，默认：0
            convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
            showButton: true,        //显示定位按钮，默认：true
            buttonPosition: 'RB',    //定位按钮停靠位置，默认：'LB'，左下角
            showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
            showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
            panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
            zoomToAccuracy: true,//定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：f
            extensions: 'all',
            pName: 'Geolocation',
            events: {
              init(o) {
                self.gd_instance = o
                // console.log("gd_indstance",self.gd_instance)
                // o 是高德地图定位插件实例
                o.getCurrentPosition((status, result) => {
                  console.log(result)
                  if (result && result.position) {
                    self.lng = result.position.lng
                    self.lat = result.position.lat
                    self.center = [self.lng, self.lat]
                    self.loaded = true
                    console.log('map init ......', self.lng, self.lat)
                    Cookies.set('map_lng', self.lng)
                    Cookies.set('map_lat', self.lat)
                    self.$nextTick()
                  }
                })

              }
            }
          },
          { pName: 'Scale' },
          { pName: 'Autocomplete' },
          { pName: 'PlaceSearch' },
          { pName: 'OverView' },
          { pName: 'ToolBar' },
          { pName: 'MapType' },
          { pName: 'PolyEditor' },
          { pName: 'CircleEditor' }

        ]
      }
    }
    ,
    created() {
      this.getList();
    },
    methods: {
      /** 查询电话位置列表 */
      getList() {
        let that = this;
        this.loading = true;
        listLocation(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          console.log("-------------获取数据------------");
          console.log(response);
          console.log(response.data);
          console.log("----------------------------------");
          let list = response.data;
          this.lastMarkerOption = response.lastLocation;
          // 遍历数组
          this.locationList = []; // 点集合
          /*list.forEach(function(it3, index) {
            // 验证点是否有效
            if(it3.longitude && it3.latitude){
                let markerOption = {
                  position: [it3.longitude, it3.latitude],
                  createTime: it3.createTime,
                  phoneSn : it3.phoneSn
                }
                that.locationList.push(markerOption)
            }else{
              console.log("------点存在值异常--------------");
            }
          });*/
          if(this.lastMarkerOption){
            let markerOption = {
              position: [this.lastMarkerOption.longitude, this.lastMarkerOption.latitude]
            }
            this.locationList.push(markerOption);
          }
          console.log("组装后的数据locationList");
          console.log(this.locationList);

          this.polylineList = []; // 折线集合
          let path = [];
          list.forEach(function(it3, index) {
            // 验证点是否有效
            if(it3.longitude && it3.latitude){
              let p = [it3.longitude, it3.latitude];
              path.push(p);
            }else{
              console.log("------点存在值异常--------------");
            }
          });

          let polylineOption = {
            id: 1,
            path: path
          };
          this.polylineList.push(polylineOption);
          console.log("组装后的数据polylineList");
          console.log(this.polylineList);
          // 跳转中心点
          if(path.length>0){
            this.center =  [this.lastMarkerOption.longitude, this.lastMarkerOption.latitude];
            console.log("center:",this.center);
            this.zoom = 15
            this.$nextTick()
          }

          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          name: null,
          longitude: null,
          latitude: null,
          createTime: null,
          remark: null,
          recordTime: null,
          phoneSn: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        console.log('-------------------------------');
        console.log(this.dateRange);
        console.log('-------------------------------');
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加电话位置";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getLocation(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改电话位置";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateLocation(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addLocation(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除电话位置编号为"' + ids + '"的数据项？').then(function() {
          return delLocation(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 清空按钮操作 */
      handleClean() {
        this.$modal.confirm('是否确认清空所有定位数据项？').then(function() {
          return cleanOperLocation();
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("清空成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('api/location/export', {
          ...this.queryParams
        }, `location_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
<style>
  .div1{
    width: 400px;
    height: 100px;
    background-color: #FCFDFF;
    opacity: 1;
    color: #7E8281;
    border: 1px solid #7E8281;
  }
  .center-in-center{
    position: absolute;
    top: 100px;
    right: 20px;
  }
</style>
